package com.zendaimoney.test.simulation.controller;

import com.zendaimoney.test.simulation.action.BaseAction;
import com.zendaimoney.test.simulation.enums.ThirdType;
import com.zendaimoney.test.simulation.utils.SpringContextHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/allinpay", produces = "application/json; charset=gbk")
@Slf4j
public class AllinpayController {

    @Autowired
    private SpringContextHelper springContextHelper;

    @RequestMapping
    @ResponseBody
    @SneakyThrows
    public String index(HttpServletRequest request) {
        log.info("process");
        String input = IOUtils.toString(request.getInputStream(), "GBK");
        log.info("input:{}", input);

        String trxCode = "";
        // 判断交易类型(划扣、签约、查询？)
        if (StringUtils.isNotEmpty(input)) {
            Document document = DocumentHelper.parseText(input);
            Element root = document.getRootElement();
            Element infoNode = root.element("INFO");
            trxCode = infoNode.elementText("TRX_CODE");
        }

        // 根据交易类型走不同的入口
        BaseAction action = springContextHelper.getTargetAction(ThirdType.ALLINPAY.getCode(), trxCode);
        return action.process(input);
    }

}
